﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using GameSchool.Models.Repositories;
using GameSchool.Models.Interfaces;
using GameSchool.Models;
using GameSchool.Models.ViewModels;

namespace GameSchool.Controllers
{
    public class HandInController : Controller
    {
        //
        // GET: /HandIn/

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Create(int? ID)
        {
            //Make sure we have the course ID
            if (ID == null)
                throw new ArgumentNullException("HandIn Create - null passed as parameter");

            //Make sure that the user is teaching this course
            var userID = (Guid)Membership.GetUser().ProviderUserKey;
            var db = new GameSchoolDBDataContext();

            var isTeacher = (from u in db.IsInCourses
                             where u.UserID == userID && u.CourseID == ID
                             select u.IsTeacher).SingleOrDefault();
            
            //If the user isn't a teacher (!= true because it might be null) nor an admin we throw him to his homepage.
            if (isTeacher != true && !(User.IsInRole("Admin")) )
                RedirectToAction("Index", "Home");

            //Everything went as expected, we start creating the new handin.
            var h = new HandIn();
            h.LevelID = ID;
            h.CourseID = (from l in db.Levels
                          where l.ID == ID
                          select l.CourseID).SingleOrDefault();
                                  
            return View(h);
        }

        [HttpPost]
        public ActionResult Create(HandIn newHandIn)
        {
            HandInRepository rep = new HandInRepository();
            AssignmentRepository repository = new AssignmentRepository();
            var newAssignment = new Assignment();

            newHandIn.Author = (Guid)Membership.GetUser().ProviderUserKey; ;
            newHandIn.DatePub = DateTime.Now;
            rep.AddHandIn(newHandIn);
            rep.Save();

            newAssignment.ResourceID = newHandIn.ID;
            newAssignment.AssignmentType = "HandIn";
            newAssignment.CourseID = newHandIn.CourseID;
            newAssignment.LevelID = newHandIn.LevelID;
            repository.AddAssignment(newAssignment);
            repository.Save();


            return RedirectToAction("Level/" + newHandIn.CourseID, "Course");
        }
       
        [HttpPost]
        public ActionResult CreateHandIn(HandIn newHandIn, Assignment newAssignment)
        {
            AssignmentRepository rep = new AssignmentRepository();
            HandInRepository repository = new HandInRepository();
            PointsRepository prep = new PointsRepository();
            newHandIn.Author = (Guid)Membership.GetUser().ProviderUserKey;
            newHandIn.DatePub = DateTime.Now;
            repository.AddHandIn(newHandIn);
            repository.Save();
          
            newAssignment.ResourceID = newHandIn.ID;
            newAssignment.AssignmentType = "HandIn";
            newAssignment.CourseID = newHandIn.CourseID;
            newAssignment.LevelID = 1;
            rep.AddAssignment(newAssignment);
            rep.Save();
            
            return RedirectToAction("Index", "Home");
        }

        [HttpGet]
        public ActionResult Edit(int? id)
        {
            if (id.HasValue)
            {
                HandInRepository rep = new HandInRepository();
                var model = rep.GetHandInByID(id);

                if (model != null)
                {
                    //If the newsItem is found in our DB we return it to the edit view..
                    return View(model);
                }
            }
            //If the int? parameter is null or the newsItem isn't fount 
            return View("NotFound");
        }

        [HttpGet]
        public ActionResult Display(int? ID)
        {
            GameSchoolDBDataContext db = new GameSchoolDBDataContext();
            HandInRepository hrep = new HandInRepository();
            PointsRepository prep = new PointsRepository();
            HandInViewModel hview = new HandInViewModel();
            int assignmentId = (from v in db.HandIns
                                from d in db.Assignments
                                where v.ID == d.ResourceID
                                where v.ID == ID
                                where d.AssignmentType == "HandIn"
                                select d.ID).SingleOrDefault();
            var getHandIn = hrep.GetHandInByID(ID);
            hview.assignmentID = assignmentId;
            hview.descr = getHandIn.Descr;
            hview.filepath = getHandIn.Filepath;
            hview.maxpoints = getHandIn.MaxPoints;
            hview.title = getHandIn.Title;
            hview.courseid = Convert.ToInt32(getHandIn.CourseID);
            Guid guid = new Guid();
            guid = (Guid)Membership.GetUser().ProviderUserKey;
            
            var completed = prep.GetAssignmentPoints(assignmentId, guid);
            if (!(completed == null))
            {
                hview.completed = true;
            }
            else
            {
                hview.completed = false;
            }


            ViewData["courseID"] = hview.courseid;
            return View(hview);


            return View(hview);

        }
        [HttpPost]
        public ActionResult Display(HandInViewModel hvm)
        {
            AssignmentScore ascore = new AssignmentScore();
            PointsRepository prep = new PointsRepository();
            Guid guid = new Guid();
            guid = (Guid)Membership.GetUser().ProviderUserKey; ;
            ascore.Points = 0;
            ascore.Filepath = hvm.returnpath;
            ascore.AssignmentID = hvm.assignmentID;
            ascore.UserID = guid;
            ascore.Bonuspoints = 0;
            ascore.UserComment = hvm.usercomment;
            ascore.IsGraded = false;
            var completed = prep.GetAssignmentPoints(hvm.assignmentID, guid);

            if (completed == null)
            {
                prep.AddPoints(ascore);
                prep.Save();
            }
          
            return RedirectToAction("index" , "Home");
        }
        public ActionResult ListHandIns(int? ID)
        {
            GameSchoolDBDataContext db = new GameSchoolDBDataContext();
            PointsRepository prep = new PointsRepository();
            HandInRepository hrep = new HandInRepository();
            UserRepository urep = new UserRepository();
            int handInAsID = (from d in db.HandIns
                              from e in db.Assignments
                              where d.ID == e.ResourceID
                              where d.ID == ID
                              where e.AssignmentType == "HandIn"
                              select e.ID).SingleOrDefault();

            var assignmentpoints = (from e in db.AssignmentScores
                                    where e.AssignmentID == handInAsID
                                    select e);

            List<PointsViewModel> list = new List<PointsViewModel>();

            foreach (var v in assignmentpoints)
            {
                UserProfile uprofile = new UserProfile();
                uprofile = urep.GetUserProfileByID(v.UserID);
                PointsViewModel pvm = new PointsViewModel();
                pvm.name = uprofile.Name;
                pvm.userID = v.UserID;
                pvm.FileLocation = v.Filepath;
                pvm.myPoints = v.Points;
                pvm.grated = v.IsGraded;
                pvm.ID = v.ID;
                pvm.assid = v.AssignmentID;
                list.Add(pvm);
            }

            return View(list);
        }
        [HttpPost]
        public ActionResult ListHandIns()
        {
           return RedirectToAction("index" , "home");
        }

        public ActionResult RateHandIns(int? ID)
        {
            GameSchoolDBDataContext db = new GameSchoolDBDataContext();
            UserRepository urep = new UserRepository();
            HandInRepository hrep = new HandInRepository();
            AssignmentScore assignmentpoints = (from e in db.AssignmentScores
                                                where e.ID == ID
                                                select e).SingleOrDefault() ;
            HandIn nhandin = new HandIn();
            int? handinID = (from e in db.AssignmentScores
                       from p in db.Assignments
                       where e.AssignmentID == assignmentpoints.AssignmentID
                       where p.ID == e.AssignmentID 
                       where e.ID == ID
                       select p.ResourceID).SingleOrDefault();
            nhandin = hrep.GetHandInByID(handinID);
                       
            PointsViewModel pvm = new PointsViewModel();
            UserProfile uprofile = new UserProfile();
            uprofile = urep.GetUserProfileByID(assignmentpoints.UserID);
            pvm.myPoints = assignmentpoints.Points;
            pvm.pointsAbove = nhandin.MaxPoints;
            pvm.ID = handinID;
            pvm.name = uprofile.Name;
            pvm.userID = assignmentpoints.UserID;
            pvm.FileLocation = assignmentpoints.Filepath;
            pvm.assid = assignmentpoints.ID;
            pvm.grated = assignmentpoints.IsGraded;
            

            return View(pvm);
        }
        [HttpPost]
        public ActionResult RateHandIns(PointsViewModel pvm)
        {
            PointsRepository prep = new PointsRepository();
            AssignmentScore ascore = new AssignmentScore();
            if (pvm.pointsAbove > pvm.myPoints)
            {
                ascore.Points =  pvm.pointsAbove;
            }
            else
            {
                ascore.Points = (int)(((double)pvm.pointsAbove/(double)pvm.myPoints)* pvm.pointsAbove);
            }


            ascore.IsGraded = pvm.grated = true;
            ascore.UserComment = pvm.comment;
            ascore.ID = (int)pvm.ID;
            ascore.UserID = pvm.userID;
            ascore.Bonuspoints = 0;
            ascore.AssignmentID = pvm.assid;


            ascore.Points = pvm.myPoints;

            prep.editScore(ascore);
            prep.Save();
            return RedirectToAction("Index", "Home");
        }
        /*
        [HttpPost]
        public ActionResult TakeHandIn()
        {
            AssignmentRepository ass = new AssignmentRepository();

            return View();
        }*/

        //Test functions 


         private IHandInRepository m_rep = null;

        public HandInController()
        {
            m_rep = new HandInRepository();
        }

        public HandInController(IHandInRepository rep)
        {
            m_rep = rep;
        }

        public ActionResult TestIndex()
        {
            var model = (from items in m_rep.GetHandIn()
                         orderby items.DatePub descending
                         select items).Take(10);
            
            return View(model);
        }
    }
}
